<?php

declare (strict_types = 1);

namespace app\service\admin\system;

use app\model\system\MenuApiModel;
use app\model\system\RoleDeptModel;
use app\model\system\RoleMenuModel;
use app\model\system\RoleModel;
use own\auth\User;
use think\facade\Db;

class RoleService
{
    public function test($param)
    {
        var_dump($param);
    }
    /**
     * 列表
     * @param array $param
     */
    public function getList(array $param)
    {
        $map = [];
        // 角色名称
        if($name = $param['name'] ?? '') {
            $map[] = ['name', 'like', '%'.trim($name).'%'];
        }
        // 角色别名
        if($alias = $param['alias'] ?? '') {
            $map[] = ['alias', 'like', '%'.trim($alias).'%'];
        }
        // 状态
        $status = $param['status'] ?? '';
        if(is_numeric($status)) {
            $map[] = ['status', $status];
        }
        $list = RoleModel::where($map)
            ->page($param['page'], $param['pageSize'])
            ->order('sort asc')
            ->select();
        return list_fmt($list, RoleModel::where($map)->count(), $param);
    }
    /**
     * 编辑
     * @param array $data 角色信息
     * @param integer $id 角色id
     */
    public function edit(array $data, int $id): bool
    {
        $auth = make(User::class);
        if($id) {
            $dept = RoleModel::find($data['id']);
            if(!$dept) {
                tips('无角色信息');
            }
            $dept->updated_by = $auth->getUser();
        } else {
            $dept = new RoleModel();
            $dept->created_by = $auth->getUser();
        }
        $dept->name = trim($data['name']);
        $dept->alias = trim($data['alias']);
        // 角色别名查重
        $this->_aliasRepeat($dept->alias, $id);
        
        $dept->status = $data['status'];
        $dept->sort = $data['sort'];
        $dept->remark = $data['remark'];
        return $dept->save();
    }
    /**
     * 角色别名查重
     * @param string $alias 角色别名
     * @param integer $id 角色id
     */
    protected function _aliasRepeat(string $alias, int $id)
    {
        $map = RoleModel::where('alias', $alias);
        if($id) {
            $map->where('id', '<>', $id);
        }
        if($map->find()) {
            tips('角色别名重复，请重新设置');
        }
    }
    /**
     * 设置角色权限
     * @param array $data
     * @param integer $id 角色id
     */
    public function permission(array $data, int $id)
    {
        $role = RoleModel::find($id);
        if(!$role) {
            tips('未找到角色信息，权限设置失败');
        }
        $role->data_scope = $data['data_scope'];
        $role->save();

        // 菜单
        $oldMenu = RoleMenuModel::where('role_id', $id)->select()->toArray();
        if($oldMenu) {
            $oldMenu = array_column($oldMenu, null, 'menu_id');
        }
        $newMenu = [];
        foreach($data['menu'] as $menu_id) {
            if(isset($oldMenu[$menu_id])) {
                unset($oldMenu[$menu_id]);
            } else {
                $newMenu[] = ['role_id' => $role->id, 'menu_id' => $menu_id];
            }
        }
        if($newMenu) {
            Db::table('o_system_role_menu')->insertAll($newMenu);
        }
        if($oldMenu) {
            RoleMenuModel::whereIn('id', array_column($oldMenu, 'id'))->delete();
        }

        // 部门
        $oldDept = RoleDeptModel::where('role_id', $id)->select()->toArray();
        if($oldDept) {
            $oldDept = array_column($oldDept, null, 'menu_id');
        }
        $newDept = [];
        foreach($data['dept'] as $dept_id) {
            if(isset($oldDept[$dept_id])) {
                unset($oldDept[$dept_id]);
            } else {
                $newDept[] = ['role_id' => $role->id, 'dept_id' => $dept_id];
            }
        }
        if($newDept) {
            Db::table('o_system_role_dept')->insertAll($newDept);
        }
        if($oldDept) {
            RoleDeptModel::whereIn('id', array_column($oldDept, 'id'))->delete();
        }
    }
    /**
     * 角色菜单
     * @param integer $id 角色id
     */
    public function roleMenuId(int $id)
    {
        return RoleMenuModel::where('role_id', $id)->column('menu_id');
    }
    /**
     * 角色部门
     * @param integer $id 角色id
     */
    public function roleDeptId(int $id)
    {
        return RoleDeptModel::where('role_id', $id)->column('dept_id');
    }
    /**
     * 角色权限验证
     * @param object $request
     */
    public static function permissionVerify($request): array
    {
        $baseUrl = $request->baseUrl();
        $method = $request->method();
        $api = MenuApiModel::where('api_method', $method)->where('code', str_replace('/', ':', $baseUrl))->find();
        if(!$api) {
            return [];
        }
        if(!RoleMenuModel::where('role_id', $request->auth->role_id)->where('menu_id', $api->menu_id)->find()) {
            tips('无操作权限');
        }
        //记录操作信息
        if($api->oper_log) {
            $param = $request->param();
            return [
                'username' => $request->auth->username, 'method'=>$method, 'router' => $baseUrl, 
                'service_name' => $api->menu_id, 'ip' => $request->ip(), 'ip_location' => '',
                'request_data' => is_array($param) ? json_encode($param) : '',
            ];
        }
    }
}